package com.tistory.login.controller;

import java.io.File;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oracle.jdbc.util.Login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.tistory.admin.adminmgr.auth.model.AdminAuthSession;
import com.tistory.admin.adminmgr.auth.model.AdminMember;
import com.tistory.admin.adminmgr.auth.model.LoginUserInfo;
import com.tistory.admin.adminmgr.auth.model.MemberConstants;
import com.tistory.admin.common.Constants;
import com.tistory.admin.common.SessionManager;
import com.tistory.admin.common.util.StringUtil;
import com.tistory.common.service.CommonService;
import com.tistory.common.vo.CommonCodeRes;
import com.tistory.common.vo.CommonReq;
import com.tistory.commons.utils.DateUtil;
import com.tistory.commons.utils.FileUploadUtil;
import com.tistory.commons.utils.SessionUtil;
import com.tistory.login.service.LoginService;
import com.tistory.login.vo.MemberDocuRes;
import com.tistory.login.vo.MemberRes;
import com.tistory.login.vo.MemberSearchInfo;

@Controller
public class LoginController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private LoginService loginService;

	@Autowired
	private CommonService commonService;


	@RequestMapping(value="login/login.do")
	public ModelAndView login() throws SQLException{
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("login/login");
		return modelAndView;
	}	

	@RequestMapping(value="/login/adminLoginExcute.do" , method=RequestMethod.POST)
	public ModelAndView adminLoginExcute(@RequestParam Map<String,Object> map , HttpSession session,HttpServletRequest request, HttpServletResponse response) throws SQLException{

		ModelAndView modelAndView = new ModelAndView();
		LoginUserInfo loginUserInfo = new LoginUserInfo();
		log.info("접근 ip==>>"+StringUtil.getLocalServerIp());
		loginUserInfo = loginService.getUser(map);
		String returnUrl = "";
		if(loginUserInfo != null){  // 로그인 성공시
			returnUrl = "login/process";

			SessionManager.setSession(request,Constants.ADMIN_AUTH_SESSION_KEY,Constants.YES);
			AdminAuthSession adminAuthSession = new AdminAuthSession();
			AdminMember adminMember = new AdminMember();
			String user_id = map.get("id").toString();

			adminMember.setId(user_id);
			adminAuthSession.setAdminMember(adminMember);

			loginUserInfo.setMbrId(user_id);

			// 세션 저장
			SessionUtil.setMemberSession(request, loginUserInfo);

			//20110424 공통에 설정된 세션시간 1800초를 1시간 3600초로 늘림  6분 세션 관리
			request.getSession(true).setMaxInactiveInterval(3600);
			Login loginM = new Login();
			// 임시정보
			SessionUtil.setAnySession(request, MemberConstants.GENERAL_USER_SESSION_KEY, loginM);

			session.setAttribute("id", map.get("id"));
			session.setAttribute("pw", map.get("password"));

			modelAndView.addObject("login", "Y");
			modelAndView.setViewName(returnUrl);

			return modelAndView;
		}else{ // 로그인 실패시
			return new ModelAndView("redirect:/login/login.do?resultCd=ERROR");
		}


	}		

	@RequestMapping(value="login/memberList.do")
	public ModelAndView memberList(HttpServletRequest request, CommonReq req) throws SQLException{

		setReqParamValue(req);
		ModelAndView modelAndView = new ModelAndView();

		List<MemberRes> memberList = loginService.getMemberList(req);
		Integer totalCount = loginService.getMemberListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("memberList", memberList);
		modelAndView.addObject("model", req);		
		modelAndView.setViewName("login/memberList");
		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		

	@RequestMapping(value="login/memberDocuList.do")
	public ModelAndView memberDocuList(HttpServletRequest request, CommonReq req) throws SQLException{

		req.setSearchValueType_1("02");// 비 관리자로 하드코딩
		setReqParamValue(req);
		ModelAndView modelAndView = new ModelAndView();

		List<MemberRes> memberDocuList = loginService.getMemberList(req);
		Integer totalCount = loginService.getMemberListCount(req);
		req.setTotalCount(totalCount);
		modelAndView.addObject("memberDocuList", memberDocuList);
		modelAndView.addObject("model", req);		
		modelAndView.setViewName("login/memberDocuList");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}		






	@RequestMapping(value="login/memberSearch.do")
	public ModelAndView memberSearch(HttpServletRequest request) throws SQLException{

		String user_id = request.getParameter("user_id");
		String editType = request.getParameter("editType");
		ModelAndView modelAndView = new ModelAndView();


		if(editType.equals("U")){	// 수정시 
			MemberSearchInfo searchInfo = new MemberSearchInfo();
			searchInfo = loginService.getMemberSearch(user_id);
			modelAndView.addObject("model", searchInfo);
		}		

		List<CommonCodeRes> commonCodeList  = commonService.getCommonCodeList("DP01");		// 은행코드 코드 가져오기

		modelAndView.addObject("editType", editType);
		modelAndView.addObject("commonCodeList", commonCodeList);
		modelAndView.setViewName("login/memberSearch");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}	

	@RequestMapping(value="login/memberDocuSearch.do")
	public ModelAndView memberDocuSearch(@RequestParam Map<String,Object> map, HttpServletRequest request, CommonReq req) throws SQLException{

		ModelAndView modelAndView = new ModelAndView();
		MemberDocuRes memberDocuRes = new MemberDocuRes();
		memberDocuRes = loginService.getFileInfo(map);

		modelAndView.addObject("model", req);
		modelAndView.addObject("vo", memberDocuRes);
		modelAndView.setViewName("login/memberDocuSearch");

		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}			



	// 이미지 파일 업로드 ajax 통신
	@RequestMapping(value="login/ajaxFileImgUpload.do", method=RequestMethod.POST)
	public @ResponseBody String ajaxFileImgUpload(@RequestParam Map<String,Object> map, HttpServletResponse response, MultipartHttpServletRequest request) throws Exception{
		// 권한체크
		SessionManager.funInit(request);
		Iterator<String> itr = request.getFileNames();
		//				MultipartFile muntiFile = request.getFile(itr.next());

		String result ="success";

		String today = DateUtil.getSysDate();
		String originFileName = "";;
		String uploadPath ="/upload/"+today+"/";
		File dir = new File(uploadPath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		if(itr.hasNext()) {
			MultipartFile mpf = request.getFile(itr.next());
			originFileName = mpf.getOriginalFilename();
			originFileName= new String(originFileName.getBytes("8859_1"),"utf-8");
			String fullPath =uploadPath+originFileName;

			File f = new File(fullPath);
			// 파일 업로드 처리 완료.
			mpf.transferTo(f);

			File file = new File(fullPath);
			String saveUploadPath ="/project/spring_ibatis/WebContent/upload/img/"+today;	    
			FileUploadUtil.uploadFile(file, saveUploadPath, originFileName); // 파일 업로드 

			String imsiUploadPath = request.getSession().getServletContext().getRealPath("/upload/img/"+today);
			String path = FileUploadUtil.uploadFile(file, imsiUploadPath, originFileName); // 파일 업로드 
			String realPath  = path.substring(path.indexOf("upload"),path.length());

			map.put("realPath","/"+realPath);
			loginService.insertFileInfo(map);	

		} else {
			result ="fail";
		}

		return result;
	}		

	// 중복 ID ajax 통신
	@RequestMapping(value="login/ajaxCheckDuplicateId.do", method=RequestMethod.POST)
	public @ResponseBody LoginUserInfo ajaxCheckDuplicateId(@RequestParam Map<String,Object> map, HttpServletResponse response, HttpServletRequest request) throws SQLException{
		// 권한체크
		SessionManager.funInit(request);
		LoginUserInfo loginUserInfo = new LoginUserInfo();
		loginUserInfo = loginService.getUser(map);

		return loginUserInfo;
	}	


	// 회원 등록및 수정
	@RequestMapping(value="login/memberConfirm.do")
	public ModelAndView memberConfirm(@RequestParam Map<String,Object> map , HttpServletRequest request) throws SQLException{
		// 권한체크
		SessionManager.funInit(request);
		String editType = request.getParameter("editType");

		if(editType.equals("C")){
			loginService.insertUserInfo(map);
		}else{
			loginService.updateUserInfo(map);
		}

		return new ModelAndView("redirect:/login/memberList.do?pageNo=1");
	}		

	// 회원 삭제
	@RequestMapping(value="login/memberDelete.do")
	public ModelAndView memberDelete(@RequestParam Map<String,Object> map , HttpServletRequest request) throws SQLException{
		// 권한체크
		SessionManager.funInit(request);
		loginService.deleteUserInfo(map);

		return new ModelAndView("redirect:/login/memberList.do?pageNo=1");
	}			

	@RequestMapping(value="login/secretUpdate.do")
	public ModelAndView secretUpdate(HttpServletRequest request) throws SQLException{


		String user_id = request.getParameter("user_id");
		ModelAndView modelAndView = new ModelAndView();


		MemberSearchInfo searchInfo = new MemberSearchInfo();
		searchInfo = loginService.getMemberSearch(user_id);
		modelAndView.addObject("model", searchInfo);

		modelAndView.setViewName("login/secretUpdate");
		// 권한체크
		modelAndView = SessionManager.init(request,modelAndView);
		return modelAndView;
	}	

	@RequestMapping(value="login/secretConfirm.do")
	public ModelAndView secretConfirm(@RequestParam Map<String,Object> map, HttpServletRequest request) throws SQLException{
		// 권한체크
		SessionManager.funInit(request);
		String user_id = request.getParameter("userId");
		String nowPassword = request.getParameter("nowPassword");
		ModelAndView modelAndView = new ModelAndView();

		MemberSearchInfo searchInfo = new MemberSearchInfo();
		searchInfo = loginService.getMemberSearch(user_id);
		if(searchInfo.getPassword().equals(nowPassword)){
			loginService.updateUserInfo(map);
			modelAndView.addObject("flag", "Y");
		}else{
			modelAndView.addObject("flag", "N");
		}
		modelAndView.setViewName("login/secretConfirm");
		return modelAndView;
	}	


	@RequestMapping("/redirect")
	public String redirect(@RequestParam("url") String url) {
		return "redirect:" + url;
	}


	private CommonReq setReqParamValue(CommonReq req){
		int listCount = 10;		
		req.setStartRow(listCount * (req.getPage()-1)) ;
		req.setEndRow(listCount);


		return req;
	}


}
